package com.example.core.model;

import com.example.core.convert.ModelToFormPropertyMap;
import com.example.utils.IdUtils;
import com.example.utils.StringUtils;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.Id;
import java.util.Date;

@Getter
@Setter
@MappedSuperclass
public abstract class BaseModel<T> implements IBaseModel {

    @JsonIgnore
    private transient ModelToFormPropertyMap modelToFormPropertyMap = null;

    @Id
    @JsonSerialize(using = ToStringSerializer.class)
    @Column(name = "fd_id")
    public String fdId;

    @Column(name = "fd_name")
    private String fdName;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Column(name = "fd_create_time")
    public Date fdCreateTime;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Column(name = "fd_update_time")
    public Date fdUpdateTime;

    @Override
    public ModelToFormPropertyMap getToFormPropertyMap() {
        if (this.modelToFormPropertyMap == null) {
            this.modelToFormPropertyMap = new ModelToFormPropertyMap();
        }
        return this.modelToFormPropertyMap;
    }

    public void recalculateFields() {
        if (StringUtils.isEmpty(this.fdId)) {
            this.fdId = IdUtils.getId();
        }
        if (this.fdCreateTime == null) {
            this.fdCreateTime = new Date();
        }
        this.fdUpdateTime = new Date();
    }
}
